package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 用户访问控制过滤
 */
@WebFilter(filterName = "LoginFilter",value = "/hello.html")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("LoginFilter 初始化");
    }

    public void destroy() {
        System.out.println("LoginFilter 销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("LoginFilter 执行过滤(前)");
        //判断是否登录
        //在会话中查找登录属性
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("loginedUser")==null){
            //说明未登录
           HttpServletResponse httpServletResponse= (HttpServletResponse)response;
            ServletContext servletContext = request.getServletContext();
            String contextPath = servletContext.getContextPath();

            String  url = contextPath+"/"+ URLEncoder.encode("验证码","utf-8")+".html";
           httpServletResponse.sendRedirect(url);
           //保存当前访问页面
            String requestURI = httpServletRequest.getRequestURI();
            System.out.println("requestURI = " + requestURI);
            session.setAttribute("requestURI",requestURI);
            return;
        }
        chain.doFilter(request, response);
        System.out.println("LoginFilter 执行过滤(后)");
    }
}
